<?php

declare (strict_types=1);

namespace app\model;


use app\BaseModel;
use think\model\concern\SoftDelete;
use think\model\relation\HasMany;


class SystemMenuModel extends BaseModel
{
    use SoftDelete;

    protected $autoWriteTimestamp = true;
    //软删除
    protected $deleteTime = 'delete_time';
    protected $hidden = ['delete_time'];
    protected $name = 'system_menu';


    public function menu(): HasMany
    {
        return $this->hasMany(SystemMenuModel::class, 'parent_id', 'id');
    }


    /**
     * 生成前端菜单
     * @param $data
     * @return array
     */
    public function generateMenuStructure($data): array
    {
        $menu_list = [];
        foreach ($data as $v) {
            $list = [
                'name'      => $v['name'],
                'path'      => $v['path'],
                'component' => $v['component'],
                'meta'      => [
                    'order'                    => $v['sorts'],
                    'title'                    => $v['title'],
                    'icon'                     => $v['icon'],
                    'affixTab'                 => $v['is_affix'] == 1,
                    'externalLink'             => $v['is_link'] == 1,
                    'keepAlive'                => $v['is_keep_alive'] == 1,
                    'hidden'                   => $v['is_hide'] == 1,
                    'menuVisibleWithForbidden' => $v['is_menuVisibleWithForbidden'] == 1,
                ],
            ];
            if ( ! empty($v['children'])) {
                $list['children'] = $this->generateMenuStructure($v['children']);
            }
            $menu_list[] = $list;
        }

        return $menu_list;
    }


    public function generateAllMenuPermissionList($res,$rules = []): array
    {
        foreach($res as &$v){
            $where = [
                ['parent_id','=',$v['id']],
                ['status','=',1],
                ['menu_type','=','menu']
            ];
            if(!empty($rules)){
                $where[] = ['id','in',$rules];
            }
            $result = self::where($where)->order('sorts asc')->select()->toArray();
            if(!empty($result)){
                $result = $this->generateAllMenuPermissionList($result);
            }
            $v['children'] = $result;
        }
        return $res;
    }


    /**
     * 生成菜单权限列表
     */
    public function generateMenuPermissionList($res): array
    {
        foreach($res as &$v){
            $result = self::where('parent_id',$v['id'])->select()->toArray();
            if(!empty($result)){
                $result = $this->generateMenuPermissionList($result);
            }
            $v['children'] = $result;
        }
        return $res;
    }
}